package com.hyd.tweet.twitter;

import com.hyd.tweet.Application;
import com.hyd.tweet.user.UserManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.RequestToken;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * (description)
 *
 * @author yiding.he
 */
public class OAuthProcessor {
    
    static final Logger log = LoggerFactory.getLogger(OAuthProcessor.class);

    private static final TwitterFactory TWITTER_FACTORY = new TwitterFactory();

    // 返回：认证地址或机器人帐号。如果用户帐号已经注册，则返回后者；否则返回前者。
    public static String process(String url, String account, HttpServletResponse response) throws TwitterException {
        
        if (UserManager.getUser(account) != null) {
            return account.split("@")[0] + "@" + Application.getAppChatDomain();
        } else {
            addCookie(response, "account", account);
            
            if (!url.endsWith("/")) {
                url = url.substring(0, url.lastIndexOf("/") + 1);
            }

            url += "/callback.jsp";

            System.out.println("url: " + url);

            Twitter twitter = TWITTER_FACTORY.getInstance();
            RequestToken requestToken = twitter.getOAuthRequestToken(url);
            addCookie(response, "token", requestToken.getToken());
            addCookie(response, "tokenSecret", requestToken.getTokenSecret());

            return requestToken.getAuthorizationURL();
        }
    }

    private static void addCookie(HttpServletResponse response, String key, String value) {
        Cookie cookie = new Cookie(key, value);
        cookie.setMaxAge(3600);
        response.addCookie(cookie);
    }
}
